
package com.wangjie.wheelview;

import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.ComponentTreeObserver;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.ScrollView;
import ohos.agp.components.Text;
import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.agp.utils.Color;
import ohos.agp.utils.Point;
import ohos.agp.utils.TextAlignment;
import ohos.app.Context;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.multimodalinput.event.TouchEvent;

import java.util.ArrayList;
import java.util.List;

/**
 * Wheel view
 */
public class WheelView extends ScrollView implements Component.TouchEventListener, Component.LayoutRefreshedListener, Component.DrawTask, ComponentTreeObserver.ScrollChangedListener {
    /**
     * * The constant TAG
     */
    public static final String TAG = WheelView.class.getSimpleName();

    /**
     * * The constant OFF_SET_DEFAULT
     */
    public static final int OFF_SET_DEFAULT = 1;

    /**
     * * The constant SCROLL_DIRECTION_UP
     */
    private static final int SCROLL_DIRECTION_UP = 0;

    /**
     * * The constant SCROLL_DIRECTION_DOWN
     */
    private static final int SCROLL_DIRECTION_DOWN = 1;

    /**
     * The constant Event handler
     */
    EventHandler eventHandler = new EventHandler(EventRunner.getMainEventRunner());


    /**
     * The constant Paint
     */
    Paint paint;

    /**
     * The constant View width
     */
    int viewWidth;

    /**
     * The constant Initial y
     */
    int initialY;

    /**
     * The constant Scroller task
     */
    Runnable scrollerTask;

    /**
     * The constant New check
     */
    int newCheck = 50;

    /**
     * The constant Item height
     */
    int itemHeight = -1;

    /**
     * Selected area border
     */
    int[] selectedAreaBorder;

    /**
     * The constant Offset
     */
    int offset = OFF_SET_DEFAULT; // 偏移量（需要在最前面和最后面补全）

    /**
     * The constant Display item count
     */
    int displayItemCount; // 每页显示的数量

    /**
     * The constant Selected index
     */
    int selectedIndex = 1;

    /**
     * Items
     */
    List<String> items;

    /**
     * The constant Context
     */
    private Context context;

    /**
     * The constant Views
     */
    private DirectionalLayout views;

    /**
     * The constant On wheel view listener
     */
    private OnWheelViewListener onWheelViewListener;

    /**
     * The constant First item
     */
    private boolean firstItem = true;

    /**
     * Wheel view
     *
     * @param context context
     */
    public WheelView(Context context) {
        super(context);
        init(context);
    }

    /**
     * Wheel view
     *
     * @param context context
     * @param attrs   attrs
     */
    public WheelView(Context context, AttrSet attrs) {
        super(context, attrs);
        init(context);
    }

    /**
     * Wheel view
     *
     * @param context  context
     * @param attrs    attrs
     * @param defStyle def style
     */
    public WheelView(Context context, AttrSet attrs, String defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

    /**
     * Get offset int
     *
     * @return the int
     */
    public int getOffset() {
        return offset;
    }

    /**
     * Set offset *
     *
     * @param offset offset
     */
    public void setOffset(int offset) {
        this.offset = offset;
    }

    /**
     * On refreshed *
     *
     * @param component component
     */
    @Override
    public void onRefreshed(Component component) {
        viewWidth = getWidth();
        LogUtil.info(TAG, "onRefreshed");
        eventHandler.postTask(new Runnable() {
            @Override
            public void run() {
                try {
                    invalidate();
                } catch (Exception e) {
                    LogUtil.info(TAG, e.getMessage());
                }
            }
        });


    }

    /**
     * On draw *
     *
     * @param component component
     * @param canvas    canvas
     */
    @Override
    public void onDraw(Component component, Canvas canvas) {
        LogUtil.info(TAG, "onDraw");
        if (viewWidth == 0) {
            viewWidth = getWidth();
            LogUtil.info(TAG, "viewWidth: " + viewWidth);
        }

        if (null == paint) {
            paint = new Paint();
            paint.setColor(new Color(Color.getIntColor("#83cde6")));
            paint.setStrokeWidth(dip2px(1f));
        }

        canvas.drawLine(new Point(viewWidth * 1 / 6, selectedAreaBorder[0]), new Point(viewWidth * 5 / 6, selectedAreaBorder[0]), paint);
        canvas.drawLine(new Point(viewWidth * 1 / 6, selectedAreaBorder[1]), new Point(viewWidth * 5 / 6, selectedAreaBorder[1]), paint);

    }

    /**
     * On scrolled
     */
    @Override
    public void onScrolled() {
        LogUtil.info(TAG, "onScrolled");
        int scrollValue = getScrollValue(AXIS_Y);
        refreshItemView(scrollValue);
    }

    /**
     * Get items list
     *
     * @return the list
     */
    private List<String> getItems() {
        return items;
    }

    /**
     * Set items *
     *
     * @param list list
     */
    public void setItems(List<String> list) {
        if (null == items) {
            items = new ArrayList<String>();
        }
        items.clear();
        items.addAll(list);

        // 前面和后面补全
        for (int i = 0; i < offset; i++) {
            items.add(0, "");
            items.add("");
        }

        initData();


    }

    /**
     * Init *
     *
     * @param context context
     */
    private void init(Context context) {
        getComponentTreeObserver().addScrolledListener(this);
        setTouchEventListener(this);
        addDrawTask(this);
        setLayoutRefreshedListener(this);
        this.context = context;
        this.enableScrollBar(AXIS_Y, false);
        views = new DirectionalLayout(context);
        views.setOrientation(DirectionalLayout.VERTICAL);
        this.addComponent(views);
        selectedAreaBorder = new int[2];
        scrollerTask = new Runnable() {
            @Override
            public void run() {

                LogUtil.info(TAG, "scrollerTask: " + itemHeight);
                int newY = getScrollValue(AXIS_Y);
                if (initialY - newY == 0) { // stopped
                    final int remainder = initialY % itemHeight;
                    final int divided = initialY / itemHeight;
                    if (remainder == 0) {
                        selectedIndex = divided + offset;
                        onSeletedCallBack();
                    } else {
                        if (remainder > itemHeight / 2) {
                            eventHandler.postTask(new Runnable() {
                                @Override
                                public void run() {
                                    WheelView.this.fluentScrollTo(0, initialY - remainder + itemHeight);
                                    selectedIndex = divided + offset + 1;
                                    onSeletedCallBack();
                                }
                            });
                        } else {
                            eventHandler.postTask(new Runnable() {
                                @Override
                                public void run() {
                                    WheelView.this.fluentScrollTo(0, initialY - remainder);
                                    selectedIndex = divided + offset;
                                    onSeletedCallBack();
                                }
                            });
                        }


                    }


                } else {
                    initialY = getScrollValue(AXIS_Y);
                    eventHandler.postTask(scrollerTask, newCheck);
                }
            }
        };


    }

    /**
     * Start scroller task
     */
    public void startScrollerTask() {

        initialY = getScrollValue(AXIS_Y);
        eventHandler.postTask(scrollerTask, newCheck);
    }

    /**
     * Init data
     */
    private void initData() {
        displayItemCount = offset * 2 + 1;

        for (String item : items) {
            views.addComponent(createView(item));
        }

        refreshItemView(0);
    }

    /**
     * Create view text
     *
     * @param item item
     * @return the text
     */
    private Text createView(String item) {
        Text tv = new Text(context);
        tv.setLayoutConfig(new ComponentContainer.LayoutConfig(LayoutConfig.MATCH_PARENT, 150));
        tv.setMultipleLine(false);
        tv.setTextSize(20, Text.TextSizeType.FP);
        tv.setText(item);
        tv.setTextAlignment(TextAlignment.CENTER);
        int padding = dip2px(15);
        tv.setPadding(padding, padding, padding, padding);
        if (firstItem) {
            tv.addDrawTask(new DrawTask() {
                @Override
                public void onDraw(Component component, Canvas canvas) {
                    LogUtil.info(TAG, "onDraw tv");
                    if (-1 == itemHeight) {
                        itemHeight = getViewMeasuredHeight(component);
                        LogUtil.info(TAG, "itemHeight: " + itemHeight);
                        views.setLayoutConfig(new ComponentContainer.LayoutConfig(LayoutConfig.MATCH_PARENT, ComponentContainer.LayoutConfig.MATCH_CONTENT));
                        DirectionalLayout.LayoutConfig lp = (DirectionalLayout.LayoutConfig) WheelView.this.getLayoutConfig();
                        WheelView.this.setLayoutConfig(new DirectionalLayout.LayoutConfig(lp.width, itemHeight * displayItemCount));
                        selectedAreaBorder[0] = itemHeight * offset;
                        selectedAreaBorder[1] = itemHeight * (offset + 1);
                    }
                }
            });
            firstItem = false;
        }

        return tv;
    }

    /**
     * Refresh item view *
     *
     * @param scrollValue scrollValue
     */
    private void refreshItemView(int scrollValue) {
        int position = scrollValue / itemHeight + offset;
        int remainder = scrollValue % itemHeight;
        int divided = scrollValue / itemHeight;

        if (remainder == 0) {
            position = divided + offset;
        } else {
            if (remainder > itemHeight / 2) {
                position = divided + offset + 1;
            }
        }

        int childSize = views.getChildCount();
        for (int i = 0; i < childSize; i++) {
            Text itemView = (Text) views.getComponentAt(i);
            if (null == itemView) {
                return;
            }
            if (position == i) {
                itemView.setTextColor(new Color(Color.getIntColor("#0288ce")));
            } else {
                itemView.setTextColor(new Color(Color.getIntColor("#bbbbbb")));
            }
        }

    }

    /**
     * On seleted call back
     */
    private void onSeletedCallBack() {
        if (null != onWheelViewListener) {
            onWheelViewListener.onSelected(selectedIndex, items.get(selectedIndex));
        }

    }

    /**
     * Set seletion *
     *
     * @param position position
     */
    public void setSeletion(int position) {
        final int nowPosition = position;
        selectedIndex = nowPosition + offset;
        eventHandler.postTask(new Runnable() {
            @Override
            public void run() {
                WheelView.this.fluentScrollTo(0, nowPosition * itemHeight);
            }
        });

    }

    /**
     * Get seleted item string
     *
     * @return the string
     */
    public String getSeletedItem() {
        return items.get(selectedIndex);
    }

    /**
     * Get seleted index int
     *
     * @return the int
     */
    public int getSeletedIndex() {
        return selectedIndex - offset;
    }

    /**
     * Do fling y *
     *
     * @param velocityY velocity y
     */
    @Override
    public void doFlingY(int velocityY) {
        super.doFlingY(velocityY / 3);
        LogUtil.info(TAG, "doFlingY");
    }

    /**
     * Do fling *
     *
     * @param velocityX velocity x
     * @param velocityY velocity y
     */
    @Override
    public void doFling(int velocityX, int velocityY) {
        super.doFling(velocityX, velocityY);
        LogUtil.info(TAG, "doFling");
    }


    /**
     * Fluent scroll by *
     *
     * @param dx dx
     * @param dy dy
     */
    @Override
    public void fluentScrollBy(int dx, int dy) {
        super.fluentScrollBy(dx, dy);
        LogUtil.info(TAG, "fluentScrollBy");
    }

    /**
     * On touch event boolean
     *
     * @param component component
     * @param ev        ev
     * @return the boolean
     */
    @Override
    public boolean onTouchEvent(Component component, TouchEvent ev) {
        if (ev.getAction() == TouchEvent.PRIMARY_POINT_UP) {
            startScrollerTask();
        }

        return true;
    }

    /**
     * Get on wheel view listener on wheel view listener
     *
     * @return the on wheel view listener
     */
    public OnWheelViewListener getOnWheelViewListener() {
        return onWheelViewListener;
    }

    /**
     * Set on wheel view listener *
     *
     * @param onWheelViewListener on wheel view listener
     */
    public void setOnWheelViewListener(OnWheelViewListener onWheelViewListener) {
        this.onWheelViewListener = onWheelViewListener;
    }

    /**
     * Dip 2 px int
     *
     * @param dpValue dp value
     * @return the int
     */
    private int dip2px(float dpValue) {
        final float scale = context.getResourceManager().getDeviceCapability().screenDensity / 160;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * Get view measured height int
     *
     * @param view view
     * @return the int
     */
    private int getViewMeasuredHeight(Component view) {
        return view.getHeight();
    }

    /**
     * On wheel view listener
     */
    public static class OnWheelViewListener {
        /**
         * On selected *
         *
         * @param selectedIndex selected index
         * @param item          item
         */
        public void onSelected(int selectedIndex, String item) {
        }
    }

}
